package com.wk.ftpserver;

import android.app.Service;
import android.content.Intent;
import android.os.Environment;
import android.os.IBinder;
import android.util.Log;

import org.apache.ftpserver.FtpServer;
import org.apache.ftpserver.FtpServerFactory;
import org.apache.ftpserver.ftplet.Authority;
import org.apache.ftpserver.ftplet.FtpException;
import org.apache.ftpserver.listener.ListenerFactory;
import org.apache.ftpserver.usermanager.impl.BaseUser;
import org.apache.ftpserver.usermanager.impl.WritePermission;
import java.util.ArrayList;
import java.util.List;

public class FtpService extends Service {
    private FtpServer ftpServer;

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    /**
     * 多次调用startService会多次执行onstartCommand。
     */
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        if(ftpServer==null){
            String userName= intent.getStringExtra("userName") ;
            String userPwd = intent.getStringExtra("userPwd");
            String shareDir = intent.getStringExtra("shareDir");
            String  port = intent.getStringExtra("ftpPort"  );
            int ftpPort = Integer.valueOf(port) ;

            try {
                release();
                startFtp(userName ,userPwd ,shareDir , ftpPort);
            } catch (FtpException e) {
                e.printStackTrace();
            }
        }
        return super.onStartCommand(intent, flags, startId);
    }

    /**
     * 如果没有销毁，多次调用startService ，onCreate 也只会执行一次
     */
    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        release();
    }


    private void startFtp(String userName , String userPwd ,String shareDir ,int ftpPort) throws FtpException {
        List<Authority> authorities = new ArrayList<Authority>();
        authorities.add(new WritePermission());

        BaseUser baseUser = new BaseUser();
        baseUser.setName(userName);
        baseUser.setPassword(userPwd);
        baseUser.setHomeDirectory(shareDir);
        baseUser.setAuthorities(authorities);

        FtpServerFactory serverFactory = new FtpServerFactory();
        serverFactory.getUserManager().save(baseUser);


        ListenerFactory factory = new ListenerFactory();
        factory.setPort(ftpPort); //设置端口号 非ROOT不可使用1024以下的端口
        serverFactory.addListener("default", factory.createListener());

        ftpServer = serverFactory.createServer();
        ftpServer.start();

        Log.i("aivin" ,"ftpServer.start()..........") ;
    }


    public void release() {
        stopFtp();
    }

    private void stopFtp() {
        Log.i("aivin" ,"stopFtp......") ;
        if (ftpServer != null) {
            ftpServer.stop();
            ftpServer = null;
        }
    }

}
